import { deepClone, numberFormat } from '@/util/util'
export const rcaNumberFormat = (value, isFen) => {
  const val = Number(parseInt(value, 10))
  const finalValue = isNaN(val) ? 0 : val
  return numberFormat((isFen ? finalValue/100 : finalValue), 2)
}

export const rcaNumberFormat0 = (value, isFen) => {
  const val = Number(value)
  const finalValue = isNaN(val) ? 0 : val
  return numberFormat((isFen ? finalValue/100 : finalValue), 2)
}
export const rcaNumberFormat4 = (value, isFen) => {
  const val = Number(value)
  const finalValue = isNaN(val) ? 0 : val
  return numberFormat((isFen ? finalValue/100 : finalValue), 2)
}

/**
    * 深度优先遍历树
    * 一个递归方法
    * @params tree:要转换的树结构数据
    * @params list:保存结果的列表结构数据，初始传list = []
    * @params parentId:当前遍历节点的父级节点id，初始为null(因为根节点无parentId)
    **/
export const toListDF = (tree, list) => {
  for (let i in tree) { //遍历最上层
    //将当前树放入list中
    var node = tree[i];
    list.push({
      ...node,
    });
    //如果有子结点,再遍历子结点
    if (node.children && node.children.length) {
      toListDF(node.children, list, node.id)  //递归
    }
  }
}

/**
 * 树转list
 */
export const treeToList = (treeList) => {
  let list = [...treeList];  //结果lsit
  treeList.forEach((tree) => {
    if (tree.children && tree.children.length) {
      toListDF(tree.children, list);  //遍历子树,并加入到list中.
    }
  })
  return list;
}

export const commonTableOption = {

  // 表格边框
  border: true,
  // 是否显示表格的斑马条纹
  stripe: true,
  // 表格列齐方式
  align: 'center',

  // 是否显示操作菜单栏（行内）
  menu: false,
  // 菜单栏对齐方式
  menuAlign: 'center',

  // 搜索菜单宽度
  searchMenuSpan: 6,

  // 是否为全屏Dialog
  dialogFullscreen: true,
  // 弹出表单的label宽度
  labelWidth: 160,

  // 是否显示表格序号
  index: true,
  indexLabel: '序号',

  // 新建按钮
  addBtn: false,
  // 勾选
  selection: false,
}

// 合计公共方法
export const summaryMethod = (param, tableOption) => {
  const { columns, data } = param;
  const copy = deepClone(tableOption)
  const columnsList = treeToList(copy.column)
  const sums = columns.map((column, index) => {
    if (index === 0) {
      return '合计';
    }
    const optionColumn = columnsList.find(c => c.prop === column.property) || {}

    if (!optionColumn.showSummary) {
      return '-'
    }

    const newData = data.map(d => {
      return d[column.property];
    })

    const total = newData.reduce((prev, curr) => {
      const value = Number(curr);
      if (!isNaN(value)) {
        return prev + Number(curr);
      } else {
        return prev;
      }
    }, 0);
    return optionColumn.formatter ? optionColumn.formatter(null, total, column.label, optionColumn) : total;

  });

  return sums;
}
